package org.grow.authfilter.service;


import org.grow.authfilter.entity.RoleInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.text.MessageFormat;
import java.util.Collection;
import java.util.List;

/**
 * @Author: xwg
 * @CreateDate: 21-7-21
 */

@Service
public class UrlDataSource implements FilterInvocationSecurityMetadataSource {


    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Override
    public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
//       Object入参o FilterInvocation:request response filterChain
        FilterInvocation fi = (FilterInvocation) o;
        HttpServletRequest request = fi.getRequest();
        String uri = request.getRequestURI();

        String method = request.getMethod().toUpperCase();
        String sql = "select r.* from Permission p " +
                "inner join PermissionRole pr on p.permissionId = pr.permissionFk " +
                "inner join RoleInfo r on r.roleId = pr.roleFk " +
                "where ? like p.pathPattern and httpMethod = ?";
        List<RoleInfo> roleInfos = jdbcTemplate.query(sql,
                new BeanPropertyRowMapper<>(RoleInfo.class),
                uri, method);
        System.out.println(MessageFormat.format("uri : {0} {1}查询到的roles {2}", uri,method,roleInfos.toString()));
        List a = roleInfos;
        return a;

    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {

        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
